﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace FySystem.IO
{
    public class LocalStorage
    {
        private static string FILE_NAME = AppDomain.CurrentDomain.BaseDirectory + "localstorage";

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Load<T>()
        {
            try
            {
                using(FileStream fs=new FileStream(FILE_NAME, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    using(StreamReader sr=new StreamReader(fs))
                    {
                        string jsn = sr.ReadToEnd();
                        if (!string.IsNullOrWhiteSpace(jsn))
                            return JsonSerializer.Deserialize<T>(jsn, new JsonSerializerOptions()
                            {
                                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                            });
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return default(T);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        public static void Save<T>(T data)
        {
            try
            {
                string jsn = string.Empty;
                if (data == null)
                    jsn = "";
                else
                    jsn = JsonSerializer.Serialize(data, new JsonSerializerOptions()
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });

                if (File.Exists(FILE_NAME))
                    File.Delete(FILE_NAME);

                using (FileStream fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine(jsn);
                        sw.Flush();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
